package com.videoweb.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.videoweb.mapper.VideoMapper;
import com.videoweb.model.Video;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;

@Service
public class VideoService extends ServiceImpl<VideoMapper, Video> {
    
    private static final Logger log = LoggerFactory.getLogger(VideoService.class);
    private final Path uploadPath = Paths.get("uploads");
    private static final List<String> ALLOWED_CONTENT_TYPES = Arrays.asList(
        "video/mp4",
        "video/webm",
        "video/quicktime"
    );
    private static final long MAX_FILE_SIZE = 1024L * 1024L * 1024L; // 1GB
    
    public VideoService() {
        try {
            Files.createDirectories(uploadPath);
        } catch (IOException e) {
            log.error("Failed to create upload directory", e);
            throw new RuntimeException("Could not create upload directory", e);
        }
    }
    
    @Transactional
    public Video uploadVideo(MultipartFile file, String title, String description, Long userId) throws IOException {
        // Validate file
        validateVideoFile(file);
        
        // Generate unique filename
        String originalFilename = file.getOriginalFilename();
        String extension = originalFilename != null ? originalFilename.substring(originalFilename.lastIndexOf(".")) : ".mp4";
        String fileName = UUID.randomUUID().toString() + extension;
        
        try {
            // Save file
            Path filePath = uploadPath.resolve(fileName);
            Files.copy(file.getInputStream(), filePath);
            
            // Create video record
            Video video = new Video();
            video.setTitle(title);
            video.setDescription(description);
            video.setFilePath(fileName);
            video.setUserId(userId);
            video.setUploadTime(LocalDateTime.now());
            
            // Save to database
            if (!this.save(video)) {
                // If database save fails, delete the uploaded file
                Files.deleteIfExists(filePath);
                throw new RuntimeException("Failed to save video information to database");
            }
            
            return video;
        } catch (IOException e) {
            log.error("Failed to save video file", e);
            throw new IOException("Failed to save video file: " + e.getMessage());
        }
    }
    
    private void validateVideoFile(MultipartFile file) {
        if (file.isEmpty()) {
            throw new IllegalArgumentException("File is empty");
        }
        
        if (file.getSize() > MAX_FILE_SIZE) {
            throw new IllegalArgumentException("File size exceeds maximum limit of 1GB");
        }
        
        if (!ALLOWED_CONTENT_TYPES.contains(file.getContentType())) {
            throw new IllegalArgumentException("Unsupported file type. Allowed types: MP4, WebM, QuickTime");
        }
    }
    
    public List<Video> getAllVideos() {
        return this.list();
    }
    
    public List<Video> getUserVideos(Long userId) {
        QueryWrapper<Video> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        return this.list(queryWrapper);
    }
    
    public java.util.Optional<Video> getVideoById(Long id) {
        QueryWrapper<Video> wrapper = new QueryWrapper<>();
        wrapper.eq("id", id)
              .eq("deleted", 0);
        return java.util.Optional.ofNullable(baseMapper.selectOne(wrapper));
    }

    public Video getVideo(Long id) {
        QueryWrapper<Video> wrapper = new QueryWrapper<>();
        wrapper.eq("id", id)
              .eq("deleted", 0);
        return baseMapper.selectOne(wrapper);
    }
    
    public boolean deleteVideo(Long id, Long userId) {
        Video video = this.getById(id);
        if (video != null && video.getUserId().equals(userId)) {
            this.removeById(id);
            // Optionally delete the file from disk
            try {
                Files.deleteIfExists(uploadPath.resolve(video.getFilePath()));
            } catch (IOException e) {
                // Log the error but don't prevent deletion from DB
                e.printStackTrace();
            }
            return true;
        }
        return false;
    }
}
